var fs=require("fs");

exports.add=[{
	 _type:"model_methods",
	_config: {name:"File"},
	AfterFetchCustom: function() {
		var rr=this._SQL().fallback_href2;
		var path=rr.F("Files","file_folder_path",this.file_folder_id);
		this.url=path+this.id+"."+this.ext;
		switch (this.type_id) {
			case 1:
				this.icon=this.url;
				break;
			case 2:
				this.icon=path+this.id+".jpg";
				break;
			default:
				this.icon=rr.F("Files","guess_icon",this.ext);
				break;
		}
	},

	AfterDeleteCustom: function() {	
		var rr=this._SQL().fallback_href2;
		var t=this;
		var path=rr.F("Files","file_folder_path",this.file_folder_id,1);
		var d=new fs.Directory(path);
		d.listFiles().forEach(function(filename) {
			var arr=filename.match(/^(\d+)(|-preview\d+\w*\d*)\.\w+$/);
			if (!arr) return;
			if (arr[1]!=t.id) return;
			f=new fs.File(path+filename);
			f.remove();
		});
	},

	AfterSaveCustom: function() {
		this.AfterFetchCustom();
	},

	MoveToFolder: function(fld_id) {
		if (fld_id==this.file_folder_id) return;
		var rr=this._SQL().fallback_href2;
		var t=this;
		var oldpath=rr.F("Files","file_folder_path",this.file_folder_id,1);
		this.file_folder_id=fld_id;
		var newpath=rr.F("Files","file_folder_path",this.file_folder_id,1);

		var d=new fs.Directory(oldpath);
		d.listFiles().forEach(function(filename) {
			var arr=filename.match(/^(\d+)(|-preview\d+\w*\d*)\.\w+$/);
			if (!arr) return;
			if (arr[1]!=t.id) return;
			f=new fs.File(oldpath+filename);
			try {
				rr.F("Files","mkdir_rec",newpath);
				f.move(newpath+filename);
			} catch(e) {
				throw new Error("Cannot move file from "+oldpath+filename+" to "+newpath+filename+" - error "+e);
			}
		});
	}
}];

